<template>
  <div>
    <div class="container">
      <div class="top">
        <p>{{ selectedItemName }}</p>
        <button>返回首页</button>
      </div>
      <div class="center">
        <div v-for="(message, index) in messages" :key="index" 
     :class="['message-item', { 'self-message': message.isSelf }]">
  <img 
    :src="message.avatar || require('../assets/logo.png')"
    class="avatar"
    :alt="message.sendUserName">
       
  <div class="message-content">
    <div class="message-header" v-if="!message.isSelf">
      <span class="username">{{ message.sendUserName }}</span>
      <span class="time">{{ formatTime(message.sendTime) }}</span>
    </div>
    <p class="message-text">{{ message.message }}</p>
    <div class="message-footer" v-if="message.isSelf">
      <span class="time">{{ formatTime(message.sendTime) }}</span>
    </div>
  </div>
</div>
      </div>
      <div class="bottom">
        <el-input
          type="textarea"
          :rows="5"
          placeholder="请输入内容"
          v-model="textarea"
          class="text-area">
        </el-input>
        <el-button type="primary" @click="sendMessage" style="margin-top:10px;">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
export default {
  name: 'ChatMain',
  data() {
    return {
      textarea: '',
      selectedItemName: '', 
      messages: [], 
      currentUser: JSON.parse(localStorage.getItem('currentUser')),
      currentTarget: null, 
    };
  },
  created() {
    this.initWebSocket();
    this.$bus.$on('item-selected', (user) => {
    console.log('收到用户:', user); // 调试输出
    this.selectedItemName = user?.name || '未知用户';
    this.currentTarget = user; // 保存完整用户对象
    this.messages = [];
  });
  },
  methods: {
    initWebSocket() {
      this.socket = new WebSocket('ws://websocket.1uu.pw/chat');

this.socket.onmessage = (event) => {
  try {
    const msg = JSON.parse(event.data);
    const isCurrentChat = 
    (msg.sendUserId === this.currentTarget?.id && 
       msg.receivUserId === this.currentUser.id) ||
      (msg.receivUserId === this.currentTarget?.id && 
       msg.sendUserId === this.currentUser.id);

    if (isCurrentChat) {
      // 去重逻辑：检查是否已存在临时消息
      const isDuplicate = this.messages.some(m => 
        m.tempId === msg.tempId || 
        (m.sendTime === msg.sendTime && m.message === msg.message)
      );

      if (!isDuplicate) {
        this.messages.push({
          ...msg,
          isSelf: msg.sendUserId === this.currentUser.id,
          status: 'sent' // 更新状态
        });
      } else {
        // 更新临时消息状态
        const index = this.messages.findIndex(m => m.tempId === msg.tempId);
        if (index > -1) {
          this.messages[index] = {
            ...this.messages[index],
            ...msg,
            status: 'sent'
          };
        }
      }
    }
  } catch (e) {
    console.error('消息解析失败:', e);
  }
};
      this.socket.onopen = () => {
        console.log('WebSocket connected');
        // 发送身份验证
        this.socket.send(JSON.stringify({
          type: 'auth',
          token: localStorage.getItem('token')
        }));
      };
    },

    handleChatMessage(msg) {
      // 判断是否属于当前会话
      if (msg.from === this.currentTarget || msg.to === this.currentTarget) {
        this.messages.push({
          id: msg.id,
          text: msg.content,
          avatar: msg.avatar || require('@/assets/logo.png'),
          timestamp: msg.timestamp,
          isSelf: msg.from === this.currentUser.id
        });
      }
    },

    sendMessage() {
  if (!this.textarea.trim() || !this.currentTarget) return;

  const tempId = Date.now() + '-' + Math.random().toString(36).substr(2, 9);

  const messageData = {
    sendUserId: this.currentUser.id,
    sendUserName: this.currentUser.name,
    receivUserId: this.currentTarget.id,
    message: this.textarea.trim(),
    sendTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    avatar: this.currentUser.avatar,
    tempId 
  };

  try {
    this.messages.push({
      ...messageData,
      isSelf: true,
      status: 'sending' // 添加发送状态
    });

    this.socket.send(JSON.stringify(messageData));
    this.textarea = '';
  } catch (error) {
    const index = this.messages.findIndex(m => m.tempId === tempId);
    if (index > -1) {
      this.messages[index].status = 'failed';
    }
    console.error('消息发送失败:', error);
  }
},
    async loadHistory(targetId) {
  try {
    this.messages = this.messages.filter(m => m.isSystem);
    const response = await this.$axios.get('/messages/history', {
      params: { 
        targetId,
        timestamp: Date.now() // 防止缓存
      },
      headers: { 
        Authorization: 'Bearer ' + localStorage.getItem('token') 
      }
    });

    if (response.data.code === 0) {
      const formatted = response.data.data.map(msg => ({
        ...msg,
        isSelf: msg.sendUserId === this.currentUser.id,
        avatar: msg.sendUserId === this.currentUser.id 
          ? this.currentUser.avatar 
          : this.currentTarget.avatar,
        sendTime: msg.sendTime || new Date().toISOString()
      }));
      
      // 保证时间顺序
      this.messages = [...formatted.sort((a, b) => 
        new Date(a.sendTime) - new Date(b.sendTime)
      )];
    }
  } catch (error) {
    console.error('加载历史消息失败:', error);
    this.messages.push({
      isSystem: true,
      message: '历史记录加载失败'
    });
  }
},
formatTime(time) {
  return moment(time).isValid() 
    ? moment(time).format('HH:mm')
    : '未知时间';
}
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close();
    }
  }

}
</script>

<style scoped>
.container {
width: calc(100vw - 400px); 
height: 100vh; 
border: 1px solid #ccc;
display: flex; 
flex-direction: column; 
}

.top {
height: 50px;
display: flex;
justify-content: space-between;
align-items: center;
margin: 0 10px;
}

.center {
width: 100%;
height: 500px; 
overflow-y: auto;
/* background-color: bisque; */
border-top: 1px solid #ccc;
}

.bottom {
height: calc(100vh - 650px); 
width: 100%;
/* padding: 10px;  */
border-top: 1px solid #ccc; 
position: relative;
}
.bottom>>>.el-textarea__inner {
border: none;
}
.bottom>>>.el-textarea__inner:focus {
outline: none;
box-shadow: none;
resize: none;
}
.el-button {
  /* background-color: brown; */
  position: absolute;
  right: 0;
  bottom: -90px;
}
.message-item {
  display: flex;
  margin: 10px;
  gap: 12px; 
}

.self-message {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.message-item.self {
  flex-direction: row-reverse; /* 发送消息右对齐 */
}

.message-content {
  background-color: #f1f1f1;
  border-radius: 12px;
  padding: 8px 12px;
  max-width: 60%;
}

.self .message-content {
  background-color: #95ec69;
}

.timestamp {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}
</style>